#include "stdafx.h"
#include "xNode.h"

namespace ck
{
	namespace xml
	{

		Node::Node(xmlNodePtr pxNode):
			m_pxNode(pxNode)
		{
			m_pxNode->_private = this;
			m_pxChild = NULL;
		}

		Node::~Node()
		{
		}
		
		const char*	Node::GetName()
		{
			if (m_name.empty())
			{
				//const char* name_gbk = NULL;
				//name_gbk = auge_encoding_convert("UTF-8", "GBK", (char*)(m_pxNode->name), strlen((char*)(m_pxNode->name)));
				//if (name_gbk != NULL)
				//{
				//	m_name = name_gbk;
				//}

				m_name = (char*)(m_pxNode->name);
			}
			return m_name.c_str();
		}

		bool Node::SetName(const char* name)
		{
			if (!name)
			{
				return false;
			}	

			//const char* name_utf8 = auge_encoding_convert("GBK", "UTF-8", name, strlen(name));
			//if (name_utf8 == NULL)
			//	return false;
			//xmlNodeSetName(m_pxNode, BAD_CAST name_utf8);

			m_name = name;
			xmlNodeSetName(m_pxNode, BAD_CAST name);

			return true;
			return true;
		}

		Node* Node::AddChild(const char* name, const char* nspace/* = NULL*/)
		{
			//const char* utf8_name = auge_encoding_convert("GBK", "UTF-8", name, strlen(name));
			//xmlNodePtr pxmlChild = CreateNewChildNode(utf8_name, ns_prefix);

			xmlNodePtr pxmlChild = CreateNewChildNode(name, nspace);
			if (pxmlChild == NULL)
			{
				return NULL;
			}
			xmlNodePtr pxmlNode = xmlAddChild(m_pxNode, pxmlChild);
			if (pxmlNode == NULL)
			{
				return NULL;
			}
			return static_cast<Node*>(pxmlNode->_private);
		}

		xmlNodePtr Node::CreateNewChildNode(const char* name, const char* nspace)
		{
			xmlNsPtr ns = NULL;
			if (m_pxNode->type != XML_ELEMENT_NODE)
			{
				return NULL;
			}

			if ((nspace != NULL) && (strlen(nspace) > 0))
			{
				ns = xmlSearchNs(m_pxNode->doc, m_pxNode, (const xmlChar*)nspace);
				if (ns == NULL)
				{
					return NULL;
				}
			}

			return xmlNewNode(ns, (const xmlChar*)name);
		}

		void Node::Reset()
		{
			if (m_pxNode)
			{
				m_pxChild = m_pxNode->children;
			}
		}

		Node* Node::NextChild()
		{
			if (!m_pxChild)
			{
				return NULL;
			}
			xmlNodePtr ptr = m_pxChild;
			m_pxChild = m_pxChild->next;
			return reinterpret_cast<Node*>(ptr->_private);
		}

		TextNode* Node::GetChildTextNode()
		{
			for (xmlNodePtr child = m_pxNode->children; child; child = child->next)
			{
				if (child->type == XML_TEXT_NODE)
				{
					return static_cast<TextNode*>(child->_private);
				}
			}
			return NULL;
		}

	}
}
